package com.rpc.center.event.listener;


import com.rpc.center.entity.PublisherNode;
import com.rpc.center.event.eventtype.PublishEvent;
import com.rpc.center.event.eventtype.EventType;
import com.rpc.center.manager.RPCServiceManager;
import com.rpc.common.entity.request.PublishDTO;
import com.rpc.common.entity.response.PublishRS;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class PublishListenter extends EventListener<PublishEvent> {
    @Autowired
    private RPCServiceManager serviceManager;

    public PublishListenter() {
        this.setEventType(EventType.PUBLISH_EVENT);
    }

    @Override
    public void actionListener(PublishEvent event) {
        PublishDTO publishDTO = event.getMessage();
        Channel channel=event.getChannel();
        String serviceID = publishDTO.getInterfaceName() + publishDTO.getVersion();
        String address = publishDTO.getHostAddress();
        int port = publishDTO.getPort();

        PublisherNode publisherNode=new PublisherNode();
        publisherNode.setAddress(publishDTO.getHostAddress());
        publisherNode.setChannel(channel);
        publisherNode.setPort(publishDTO.getPort());
        publisherNode.setLastKeepLiveTime(System.currentTimeMillis());
        publisherNode.setOpenHttp(publishDTO.isOpenHttp());
        publisherNode.setServiceID(serviceID);

        serviceManager.regist(serviceID,publisherNode);//服务注册

        PublishRS publishRS = new PublishRS();
        publishRS.setMsg("注册成功");
        publishRS.setSuccess(true);
        channel.writeAndFlush(publishRS);


        //todo 向其他已确定消费此服务的消费方推送此服务发布方上线通知
    }
}
